#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include "log.h"


/** \brief Minimal level required for logging
 *
 * Only messages with a level greater than LOG_min_level are added to logfile.
 * There is one exception: debug messages are logged if and only if DEBUG is
 * defined.
 *
 */
#ifdef DEBUG
static int LOG_level = LOG_ALL;
#else
static int LOG_level = LOG_ALL & (~LOG_DEBUG);
#endif


/// Logfile file pointer
static FILE* LOG_fp = NULL;


int LOG_set_file(const char* fname)
{
  LOG_close();

  if( fname == NULL )
    LOG_fp = stderr;
  else
    LOG_fp = fopen(fname, "a");

  return ( LOG_fp == NULL ) ? -1 : 0 ;
}


void LOG_close()
{
  if( LOG_fp != NULL && LOG_fp != stderr )
    fclose(LOG_fp);
  LOG_fp = NULL;
}


int LOG_add(int level, const char* msg, ...)
{
  va_list ap;

  char strTime[LOG_TIME_LEN];
  time_t now;

  int rv=0;

  if( (level & LOG_level) == 0 )
    return 0;

  if( (now = time(NULL)) == -1 )
    return -1;

  if( strftime(strTime, LOG_TIME_LEN, LOG_TIME_FORMAT, localtime(&now)) == 0 )
    return -1;

  rv |= (fprintf(LOG_fp, "%s - %s: ",
                  strTime, LOG_LEVEL_TEXT(level)) < 0);
  
  va_start( ap, msg);

  rv |= (vfprintf(LOG_fp, msg, ap) < 0);

  va_end( ap );
  
  rv |= (fputc('\n',LOG_fp) == EOF);

  fflush(LOG_fp);
  
  return rv?-1:0;

}


inline void LOG_set_level(int level)
{
  LOG_level = level;
}


